using DemoWebapi01;
using DemoWebapi01.Models;
using DemoWebapi01.MyServices;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Scalar.AspNetCore;
using System.Net;
using System.Text;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
    options.JsonSerializerOptions.PropertyNamingPolicy = null; // 保持属性原名
}); ;
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

builder.Services.AddDbContext<MyDbContext>();
builder.Services.AddScoped<IEmailService, EmailService>();
//内存缓存
builder.Services.AddMemoryCache();
// 从配置文件中读取JWT设置
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings"));
var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
builder.Services.AddScoped<IAuthService, AuthService>();

// 添加 JWT 认证服务
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = jwtSettings?.Issuer,
        ValidAudience = jwtSettings?.Audience,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings?.SecretKey ?? "")),
        ClockSkew = TimeSpan.FromMinutes(5)
    };
});
builder.Services.AddAuthorization();
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("AdminOnly", policy =>
        policy.RequireRole("管理员", "超级管理员"))// 必须是管理员或超级管理员，满足其一即可
    .AddPolicy("UserOnly", policy =>
        policy.RequireRole("User"))
    .AddPolicy("EmailActivePolicy", policy =>
    {
        policy.RequireClaim("Department", "IT");  // 必须属于 IT 部门
        policy.RequireAssertion(context =>        // 自定义逻辑（例如检查用户状态）
                context.User.HasClaim(c => c.Type == "IsActive" && c.Value == "true"));
    })
    ;
// 设置监听端口为 4999
builder.WebHost.UseUrls("http://localhost:4999");
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
    policy =>
    {
        policy.WithOrigins("http://localhost:5173") // 允许的前端地址
            .AllowAnyMethod()                     // 允许所有HTTP方法
            .AllowAnyHeader()                     // 允许所有请求头
            .AllowCredentials();                  // 允许凭证（如Cookie）
    });
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    //启动项目后，访问 /scalar/v1 即可查看 Scalar 提供的交互式 API 文档。
    app.MapScalarApiReference(options =>
    {
        options.WithTitle("My Custom API"); // 设置标题
        options.WithTheme(ScalarTheme.BluePlanet); // 设置主题
        options.WithSidebar(true); // 是否隐藏侧边栏
    });
}
app.UseHttpsRedirection();

app.UseCors("AllowSpecificOrigin");

app.UseAuthorization();

app.MapControllers();
app.MapGet("/", () => "Hello world!");
app.Run();
